package com.bing.dao.impl;

import com.bing.dao.TUrlDao;
import com.bing.entity.Link;
import com.bing.entity.TUrl;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 * Created by kaibb on 2016/6/3.
 */
@Repository
public class TUrlDaoImpl extends BaseDaoImpl<TUrl, Long> implements TUrlDao {
    @Override
    public Set<TUrl> findBy(int scanCount,String taskId) {
        Map<String, Object> param = new HashMap<>();
        param.put("taskId", taskId);
        param.put("scanCount", scanCount);
        final List<TUrl> byHQL = this.findByHQL("from TUrl where scanCount<=:scanCount and taskId=:taskId", param);
        return new HashSet<>(byHQL);
    }

    private boolean isExist(String url) {
        Map<String, Object> param = new HashMap<>();
        param.put("url", url);
        final Object byHQLOne = this.findByHQLOne("from TUrl where url=:url", param);
        return byHQLOne != null;
    }

    @Override
    public void update(Set<TUrl> tUrls) {
        for (TUrl tUrl : tUrls) {
            tUrl.setScanCount(tUrl.getScanCount() + 1);
            this.update(tUrl);
        }
    }

    @Override
    public void insert(Set<TUrl> tUrls) {
        for (TUrl tUrl : tUrls) {
            if(!this.isExist(tUrl.getUrl())){
                this.save(tUrl);
            }
        }
    }
}
